package com.keyidea.jfxui.core.system;

import cn.hutool.core.bean.BeanUtil;
import com.keyidea.jfxui.core.constant.UserConstants;
import com.keyidea.jfxui.core.system.domain.AjaxResult;
import com.keyidea.jfxui.core.system.sqlite.entity.SysDept;
import com.keyidea.jfxui.core.system.sqlite.mapper.SysDeptMapper;
import com.keyidea.jfxui.core.system.vo.TreeSelect;
import com.keyidea.jfxui.core.util.StringUtils;
import feign.Param;
import feign.RequestLine;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门管理 信息操作处理
 */
@Service
@RequiredArgsConstructor
public class SysDepartmentService extends BaseService {

    private final SysDeptMapper sysDeptMapper;

    /**
     * 获取部门列表
     */
    public AjaxResult list(Map<String, Object> map) {
        SysDept param = BeanUtil.toBean(map, SysDept.class);
        List<SysDept> depts = sysDeptMapper.selectDeptList(param);
        return success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    public AjaxResult excludeChild(Long deptId) {
        List<SysDept> depts = sysDeptMapper.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    public AjaxResult getInfo(Long deptId) {
        return success(sysDeptMapper.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    public AjaxResult add(SysDept dept) {
        if (!checkDeptNameUnique(dept)) {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return toAjax(sysDeptMapper.insertDept(dept));
    }

    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = sysDeptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改部门
     */
    public AjaxResult edit(SysDept dept) {
        Long deptId = dept.getDeptId();
        if (!checkDeptNameUnique(dept)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && sysDeptMapper.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(sysDeptMapper.updateDept(dept));
    }

    /**
     * 删除部门
     */
    public AjaxResult remove(@Param("deptId") Long deptId) {
        if (hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除");
        }
        if (checkDeptExistUser(deptId)) {
            return warn("部门存在用户,不允许删除");
        }
        return toAjax(sysDeptMapper.deleteDeptById(deptId));
    }

    public boolean hasChildByDeptId(Long deptId) {
        int result = sysDeptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    public boolean checkDeptExistUser(Long deptId) {
        int result = sysDeptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        List<SysDept> depts = sysDeptMapper.selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
}
